package com.hgx.captcha.server.rest;

import com.hgx.captcha.server.easy.captcha.Captcha;
import com.hgx.captcha.server.easy.captcha.GifCaptcha;
import com.hgx.captcha.server.response.PictureValidationVO;
import com.hgx.common.rest.response.CommonResponse;
import com.hgx.common.util.Base64Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.util.UUID;

/**
 * Description: Easy验证码
 * Author: hanguixian
 * CreateDate: 2019/08/13 15:50
 * Modified by:
 */
@RestController("easyCaptchaController")
@RequestMapping(value = "easyCaptcha")
@Api(tags = "Easy验证码")
@Slf4j
public class EasyCaptchaController {

    /**
     * 生成验证码
     */
    @ApiOperation(value = "生成验证码")
    @ApiResponse(code = 500, message = "服务器出错，生成验证码失败")
    @GetMapping(value = "/get")
    public CommonResponse<PictureValidationVO> get() {

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        // 三个参数分别为宽、高、位数
        GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 4);

        // 设置字体
        gifCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置

        // 设置类型，纯数字、纯字母、字母数字混合
        gifCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);

        // 生成的验证码
        String code = gifCaptcha.text();

        // 输出图片流
        gifCaptcha.out(out);

        String base64Str = Base64Utils.getImageBase64String(out.toByteArray());

        PictureValidationVO pictureValidationVO = new PictureValidationVO();
        pictureValidationVO.setUuid(UUID.randomUUID().toString().replaceAll("-",""));
        pictureValidationVO.setImgBase64(base64Str);

        log.info("Easy验证码生成完成,内容为:{}，返回数据:{}", code, pictureValidationVO);
        return CommonResponse.ok(pictureValidationVO);

    }
}
